package com.ezlcp.form.task;

import com.alibaba.nacos.api.config.ConfigService;
import com.ezlcp.commons.tool.StringUtils;
import com.ezlcp.commons.utils.NacosUtils;
import com.ezlcp.form.service.DatasourceServiceImpl;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.stereotype.Component;


/**
 * @author Elwin ZHANG
 * @description: 仅运行一次的任务<br />
 * @date 2023/6/6 17:33
 */
@Component
@Slf4j
public class RunOnceTaskTwo implements ApplicationContextAware {

    @Lazy
    @Resource
    private NacosUtils nacosUtils;

    @Lazy
    @Resource
    private DatasourceServiceImpl datasourceService;

    private ApplicationContext context;
    private ScheduledAnnotationBeanPostProcessor processor;

    //程序启动后5秒开始检测Nacos中数据源是否存在（防止系统初始化时该值为空引发异常）
    @Scheduled(fixedDelayString = "5000", initialDelay = 5000)
    @SneakyThrows
    public void checkNacosSetting() {
        System.out.println("RunOnceTaskTwo执行定时任务-开始");
        ConfigService service = nacosUtils.getConfigService("");
        //先根据配置初始化加载全部数据源
        var config = service.getConfig(NacosUtils.KEY_OF_DATASOURCE, "", NacosUtils.READ_TIME_OUT_MS);
        nacosUtils.closeService(service);
        if (StringUtils.isEmpty(config)) {
            datasourceService.pushAll2Nacos();
        }
        stopTask(this);
        System.out.println("RunOnceTaskTwo执行定时任务-结束");
    }

    @PostConstruct
    public void initProcessor() {
        processor = (ScheduledAnnotationBeanPostProcessor) context.getBean("org.springframework.context.annotation.internalScheduledAnnotationProcessor");
    }

    public void stopTask(Object bean) {
        processor.postProcessBeforeDestruction(bean, null);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}
